﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace WBasicClassLib.Logger 
{
    /// <summary>
    /// 日志记录类
    /// </summary>
    public class Logger : IDisposable
    {
        #region 属性

        #region 私有属性

        /// <summary>
        /// 指向所要写Log的输入流的TextWriter对象
        /// </summary>
        private TextWriter LogWriter { get; set; }

        /// <summary>
        /// Log文件对象
        /// </summary>
        private FileStream FileObject { get; set; }

        #endregion

        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数，默认绑定到控制台输入流上（注意只能应用在控制台工程中）
        /// </summary>
        public Logger()
        {
            LogWriter = Console.Out;
        }

        /// <summary>
        /// 构造函数，绑定到Filename所指向的文件上，写入方式为Append
        /// </summary>
        /// <param name="Filename">Log文件路径</param>
        /// <param name="EncodingObject">文件编码类型</param>
        public Logger(string Filename, Encoding EncodingKind)
        {
            if (!File.Exists(Filename))
            {
                FileStream Fs = File.Create(Filename);
                Fs.Close();
            }
            LogWriter = new StreamWriter(File.Open(Filename, FileMode.Append | FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read), EncodingKind);
        }

        #endregion

        #region 方法

        #region 公有方法

        /// <summary>
        /// 将Log写入到输入流中
        /// </summary>
        /// <param name="LogInfo">Log内容</param>
        public void WriteLog(string LogInfo)
        {
            LogWriter.WriteLine(DecorateLog(LogInfo));
            LogWriter.Flush();
        }

        /// <summary>
        /// 关闭Log输入流
        /// </summary>
        public void Close()
        {
            if (this.LogWriter != null)
            {
                try
                {
                    this.LogWriter.Close();
                    this.LogWriter = null;
                }
                catch { }
            }
        }

        /// <summary>
        /// 释放当前对象占用的内存
        /// </summary>
        public void Dispose()
        {
            this.Close();
            GC.SuppressFinalize(this);
        }

        #endregion 

        #region 私有方法

        /// <summary>
        /// 给原始Log信息转变为定义的Log格式，该方法可重载
        /// </summary>
        /// <param name="LogInfo">原始Log内容</param>
        /// <returns>修改后的Log内容</returns>
        public virtual string DecorateLog(string LogInfo)
        {
            return "[" + DateTime.Now.ToString() + "]" + LogInfo;
        }

        #endregion

        #endregion
    }
}
